package com.drd.dt.modular.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.drd.dt.common.Constant;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import com.drd.dt.modular.dao.GoldCoinMapper;
import com.drd.dt.modular.service.GoldCoinService;
import com.drd.dt.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 86514 on 2019/3/25.
 */
@Service
@Transactional
public class GoldCoinServiceImpl implements GoldCoinService {
    private static final Logger logger = LoggerFactory.getLogger(GoldCoinServiceImpl.class);

    @Autowired
    private GoldCoinMapper goldCoinMapper;

    /**
     * 用户登录获取随机金币
     **/
    @Override
    public Tip getRandomCoin(Integer user_id,String token_id) throws Exception {
        if (StringUtils.isEmpty(user_id) || StringUtils.isEmpty(token_id)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        //获取金币时间，判断今天是否已获得金币
        Map<String, String> info = goldCoinMapper.getCoin(user_id);
        String coinDate = info.get("coin_time");
        String now = Constant.y_M_d.format(new Date());
        if (!StringUtils.isEmpty(coinDate) && coinDate.equals(now)) {
            throw new BussinessException(BizExceptionEnum.GOLD_COIN_GET_ERROR);
        }
        //产生的是1-10的随机金币数
        Random random = new Random();
        int goldCoin = random.nextInt(10) + 1;

        Map param = new HashMap();
        String createTime = Constant.y_M_d_H_m_s.format(new Date());
        param.put("userId", user_id);
        param.put("goldCoin", goldCoin);
        param.put("createTime", createTime);

        //更新用户金币数
        goldCoinMapper.updateUserCoin(param);
        //插入金币记录到balancedetail表
        param.put("action_type", 1);
        param.put("remark", "登陆获取金币");
        goldCoinMapper.insertCoinDetail(param);

        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), "恭喜获得" + goldCoin + "枚金币", goldCoin);
    }

    /**
     * 金币兑换红包
     **/
    @Override
    public Tip exchangeRed(Integer user_id,String token_id,Integer coin) throws Exception {
        if (StringUtils.isEmpty(user_id) || StringUtils.isEmpty(token_id) || StringUtils.isEmpty(coin)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        //获取已有金币数量，判断能否兑换
        Map<String, String> info = goldCoinMapper.getCoinInfo(user_id);
        String exchange_time = info.get("exchange_time");//最近兑换同等金币时间
        String nowDate = Constant.y_M_d.format(new Date());
        if (exchange_time.equals(nowDate)) {//本月已兑换
            logger.info("【"+BizExceptionEnum.GOLD_COIN_EXCHANGE_ERROR.getMessage()+"】");
            return ResultUtil.result(BizExceptionEnum.GOLD_COIN_EXCHANGE_ERROR.getCode(), BizExceptionEnum.GOLD_COIN_EXCHANGE_ERROR.getMessage());
        }
        Integer coinNum = Integer.valueOf(info.get("gold_coin"));//用户持有的金币数量
        Integer exchangeCoin = Integer.valueOf(coin);//用户欲兑换的金币数量
        if (coinNum > 0 && exchangeCoin > 0 && coinNum >= exchangeCoin) {
            Map param = new HashMap();
            //金币兑换红包金额
            Integer money = exchangeCoinEUM(exchangeCoin);
            if (money > 0){
                param.put("money", money);
                param.put("userId", user_id);
                param.put("goldCoin", exchangeCoin);
                goldCoinMapper.updateUserRedpacket(param);//更新用户金币
                param.put("action_type", 2);
                param.put("remark", "金币兑红包");
                SimpleDateFormat sdf = Constant.y_M_d_H_m_s;
                param.put("createTime", sdf.format(new Date()));
                goldCoinMapper.insertCoinDetail(param);//插入金币详情表
                param.put("action_type", "1");
                goldCoinMapper.insertRedpacketDetail(param);//插入红包明细表
                //获取30天后时间(红包过期时间)
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.DATE, 30);
                String expire_time = sdf.format(cal.getTime());
                param.put("expire_time", expire_time);
                param.put("status", 1);
                goldCoinMapper.insertRedpacket(param);//插入红包表
            }
        } else {
            throw new BussinessException(BizExceptionEnum.GOLD_COIN_NOT_ENOUGH_ERROR);
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

    /**
     * 使用红包
     */
    @Override
    public Integer userRedpacket(String user_id) throws Exception {
        if (!StringUtils.isEmpty(user_id)) {
            //获取用户最近兑换且未过期的红包
            Map<String, Integer> map = goldCoinMapper.getLatestOneRedpacket(user_id);
            if (null == map) {
                return 0;
            }
            Integer id = map.get("id");
            Integer money = map.get("money");
            goldCoinMapper.updateRedpacketStatus(id);//修改红包使用状态
            Map param = new HashMap();
            param.put("userId", user_id);
            param.put("goldCoin", exchangeRedpacketEUM(money));
            param.put("money", money);
            param.put("action_type", 2);
            param.put("remark", "订单使用红包");
            param.put("createTime", Constant.y_M_d_H_m_s.format(new Date()));
            goldCoinMapper.insertRedpacketDetail(param);
            return money;
        } else {
            logger.info("【用户ID为空，下单使用红包失败...】");
            return 0;
        }
    }

    /**
     * 订单结算时给用户返下单时的红包
     *
     * @param order_id
     */
   /* @Override
    public void rebateUserRedpacket(String order_id) throws Exception {
        if (!StringUtils.isEmpty(order_id)) {
            //通过订单id在订单表获取红包信息
            Map<String, String> info = goldCoinMapper.getRedPackageInfoByOrderId(order_id);
            if (null == info || info.size() < 1) {
                logger.info("【未找到订单编号为*" + order_id + "*的订单...】");
                return;
            }
            String user_id = info.get("user_id");
            String redpacket = info.get("redpacket");//红包金额
            Map map = goldCoinMapper.getRPInfoFBanlanceDetail(order_id);
            String money = "";
            if (null != map) {
                money = String.valueOf(map.get("money"));//返利红包金额
            }
            if (StringUtils.isEmpty(user_id)) {
                logger.info("【订单号为*" + order_id + "*的用户ID为空，返红包失败...】");
                return;
            }
            if (StringUtils.isEmpty(redpacket) || Integer.valueOf(redpacket) < 1 || !StringUtils.isEmpty(money)) {
                return;
            }
           *//* Map param = new HashMap();
            param.put("user_id", user_id);
            param.put("money", redpacket);
            goldCoinMapper.updateUserBalance(param);//将红包加入用户余额
            param.put("action_type", 1);
            param.put("type", 13);
            param.put("remark", "订单红包返利");
            param.put("time", Constant.y_M_d_H_m_s.format(new Date()));
            param.put("order_id", order_id);
            goldCoinMapper.insertBalanceDetail(param);//红包返利信息存入balancedetail*//*
            testMoneyService.addRedPacket(Integer.parseInt(user_id),order_id,Double.parseDouble(redpacket));
        } else {
            logger.info("【传入订单编号为空，用户返红包失败...】");
        }
    }*/

    /**
     * 我的红包列表
     **/
    @Override
    public Tip myRedpacket(Integer user_id,String token_id,Integer page) throws Exception {
        if (StringUtils.isEmpty(user_id) || StringUtils.isEmpty(token_id) || StringUtils.isEmpty(page)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        Integer pageSize = Constant.PAGE_SIZE_20;
        Integer start = (page - 1) * pageSize;
        Map param = new HashMap();
        param.put("user_id", user_id);
        param.put("start", start);
        param.put("pageSize", pageSize);
        List<Map> rebateRedpacketInfo = goldCoinMapper.selectRebateRedpacketInfo(param);
        JSONArray result = new JSONArray();
        rebateRedpacketInfo.stream().forEach(t -> {
            JSONObject rebate = new JSONObject();
            String create_time = String.valueOf(t.get("create_time"));
            Integer money = Integer.valueOf(String.valueOf(t.get("money")));
            String expire_time = String.valueOf(t.get("expire_time"));
            Integer coin = exchangeRedpacketEUM(money);
            rebate.put("money", money);
            rebate.put("coin", coin);
            rebate.put("create_time", create_time);
            rebate.put("expire_time", expire_time);
            rebate.put("title", "返利红包");
            result.add(rebate);
        });
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
    }


    /**
     * 红包兑换金币比例
     *
     * @return
     */
    private static Integer exchangeRedpacketEUM(Integer money) {
        Integer coin ;
        switch (money) {
            case 1:
                coin = 30;
                break;
            case 3:
                coin = 90;
                break;
            case 5:
                coin = 150;
                break;
            case 10:
                coin = 200;
                break;
            case 15:
                coin = 300;
                break;
            case 20:
                coin = 400;
                break;
            default:
                coin = 0;
                break;
        }
        return coin;
    }

    /**
     * 金币兑换红包比例
     *
     * @param coin
     * @return
     */
    private static Integer exchangeCoinEUM(Integer coin) {
        Integer money ;
        switch (coin) {
            case 30:
                money = 1;
                break;
            case 90:
                money = 3;
                break;
            case 150:
                money = 5;
                break;
            case 200:
                money = 10;
                break;
            case 300:
                money = 15;
                break;
            case 400:
                money = 20;
                break;
            default:
                money = 0;
                break;
        }
        return money;
    }

}
